<!-- 跟单-发起策略详情 -->
<template>
  <div class="bg bg1" @rightBtn="rightBtn" @viewappear="viewappear">

    <template  v-if="info">
      <scroller class="scroller">

        <!-- 头信息 -->
        <div class="head bg2">

          <div class="row acenter mb40">

            <div class="row acenter" @click="userClick">
              <LImage class="img-avatar" :src="info.avatar"></LImage>
              <text class ="font32 text1">{{info.nickName}}</text>
            </div>

            
            <div v-if="info.isFollow" class="but-follow no1" @click="httpsCancelFollowUser">
              <text class="font24 text1">取注</text>
            </div>
            <div v-else class="but-follow main1" @click="httpsFollowUser">
              <text class="font24 text1">关注</text>
            </div>
          </div>

          <div class="row acenter mb10">
            <text class ="font32 text1">{{info.strategyName}}</text>

            <div v-if="info.contractStr" :class="['contrac', Config.upDownBg(info.contractNum)]" >
              <text class="font20 text1">{{info.contractStr}}</text>
            </div>
          </div>

          <text class ="font24 text1 mb20">{{info.pairStrx}}</text>

          <text class ="font20 text3">{{'运行时间：'+info.startTime+'-'+'至今'}}</text>
          <text class ="font20 text3">{{'运行时长：'+info.timeLnegth}}</text>
        </div>

        <!-- 策略表现 -->
        <div class="title">
          <div class="line main1"></div>
          <text class="font28 text1">{{T("策略表现")}}</text>
        </div>
        <div class="strategy bg2">

          <div class="strategy-info bg3">
            <div class="column">
              <text class="font24 text3 mb10">{{T('总投入')+'('+info.investCoin+')'}}</text>
              <text class="font32 text1">{{info.investCoinnNum}}</text>
            </div>
            <div class="column aend">
              <text class="font24 text3 mb10">{{T('总收益')+'('+info.investCoin+')'}}</text>
              <text :class="['font32', Config.upDownFont(info.realEarnings)]">{{info.realEarnings+'('+info.realEarningsRate+'%)'}}</text>
            </div>
          </div>

          <div class="strategy-data">
            
            <div class="row mb20">
              <div class="column all">
                <text class="font24 text3 mb10">{{info.contractStr ? T('账户权益') : T('实现盈亏')}}</text>
                <text v-if="info.contractStr" class="font24 text1">{{info.marginBalance}}</text>
                <text v-else :class="['font24', Config.upDownFont(info.earnings)]">{{info.earnings}}</text>
              </div>

              <div class="column all">
                <text class="font24 text3 mb10">{{info.contractStr?T('持仓盈亏'):T('浮动盈亏')}}</text>
                <text :class="['font24', Config.upDownFont(info.floatEarnings)]">{{info.floatEarnings}}</text>
              </div>

              <div class="column all aend">
                <text class="font24 text3 mb10">{{T('总年化')}}</text>
                <text :class="['font24', Config.upDownFont(info.realYearIncome)]">{{info.realYearIncome+'%'}}</text>
              </div>
            </div>

            <div class="row">
              <div class="column all">
                <text class="font24 text3 mb10">{{T('交易笔数')}}</text>
                <text class="font24 text1">{{info.orderNumber}}</text>
              </div>

              <div class="column all">
                <text class="font24 text3 mb10">{{T('交易额')}}</text>
                <text class="font24 text1">{{info.tradeMoney}}</text>
              </div>

              <div class="column all aend">
                <text class="font24 text3 mb10">{{T('最大回撤')}}</text>
                <text class="font24 text1">{{info.maxDrawdown+'%'}}</text>
              </div>
            </div>
          </div>
        </div>

        <!-- 分类 -->
        <VSubMenu class="menu" :menus="menus" :menu="menu" @menuClick="menuClick" />
        <div class="content">
          <!--参数-->
          <div class="size bg2" v-if="menu==0">
            <div class="row jbetween" :class="[index<info.params.length-1 ? 'mb20' :'']" 
            v-for="(item, index) in info.params" :key="index">
              <text class="font24 text2">{{item.title}}</text>
              <text class="font24 text1">{{item.value}}</text>
            </div>
          </div>

          <!--历史操作-->
          <div class="size bg2" v-if="menu==1">
            <div class="column" :class="[index<logs.length-1 ? 'mb40' :'']" 
            v-for="(item, index) in logs" :key="index">
              <text class="font24 text2 mb20">{{item.time}}</text>
              <text class="font24 text1 mb10">{{item.title}}</text>
              <text class="size-text text2">{{item.text}}</text>
            </div>
          </div>

          <!--收益走势图-->
          <div class="size" v-if="menu==2">
            <div class="row acenter">
              <text class="font28 text1 all">{{T('收益分析')}}</text>
              <div class="line-chart-color main1"></div>
              <text class="font24 text2">{{T("总收益率")}}</text>
            </div>
            <WeexLineChart class="line-chart" :data="lineChartData"></WeexLineChart>
          </div>

          <!--不是VIP-->
          <div class="vip-tips" v-if="!isVip">
            <LImage class="img-sigh" :src="Config.img('sigh.png')"></LImage>
            <text class="font24 text2 mb40">{{T('抱歉！当前内容仅会员才能查看。')}}</text>
            <div class="vip-but main1" @click="opVipClick">
              <text class="font28 text1">{{T('去开通会员>>')}}</text>
            </div>
          </div>
        </div>
      </scroller>
      
      <div class="bottom bg3" v-if="isVip">
        <div class="but main1" @click="copyClick">
          <text class="font32 text1">{{T("复制参数")}}</text>
        </div>
      </div>
    </template>
  </div>
  
</template>

<script>
import jconfig from "@/_js/config";
import jnavigator from "@/_js/navigator";
import jmodal from "@/_js/modal";
import jbroadcast from "@/_js/broadcast";
import jmath from "@/_js/math";
import jvlink from "@/_js/vlink";
import jhttps from "@/_js/https";
import jtime from "@/_js/time";

const weexFunction = weex.requireModule("WeexFunction");

import I18N from "@/_i18n/i18n";
var T = I18N.t;
weexFunction.setTitle(T('跟单策略'));
weexFunction.setRightBtn(T("分享"));

import VSubMenu from '@/_public/VSubMenu.vue'
export default {
  components:{
    VSubMenu,
  },

  data() {
    return {
      T:T,
      Config:jconfig,
      
      executeId:"",//执行id
      info:undefined, //展示数据
      copy:undefined, //复制参数
      logs:undefined, //操作日记
      lineChartData:undefined, //收益曲线
      isVip:false, //true 会员

      menus:['策略参数', '历史操作', '收益曲线'],
      menu:0,
    };
  },

  mounted() {
    jconfig.init(()=>{},[jconfig.OPT_UP_DOWN]);
    this.executeId = jnavigator.getParam('executeId');
    this.viewappear();
  },

  methods: {
    
    viewappear() {
      this.httpQueryExecuteDetail();
      this.httpQueryIncomeLine();
      this.httpQueryStrategyLogList();
      this.httpUserInfo();
    },
    
    initData(data) {

      var info = {
        'strategyName':'', //策略名称
        'contractNum':0, //合约方向 0多 1空 2双向
        'contractStr':'', //合约方向
        'pairStr':'', //交易对,
        'pairStrx':'',//交易对组合
        'startTime':'', //启动时间

        'investCoin':'', //投资币
        'investCoinnNum':'', //总投入

        'realEarnings':'', //总收益
        'realEarningsRate':'', //收益率

        'earnings':'', //实现盈亏-账户权益
        'floatEarnings':'', //浮动盈亏-持仓盈亏
        'realYearIncome':'', //总年化

        'orderNumber':'', //交易笔数
        'tradeMoney':'', //交易额
        'maxDrawdown':'', //最大回撤

        'params':[], //参数数组
      };

      var user = data.user;
      var tradeMoney = data.tradeMoney;
      var position = data.position;
      var execute = data.execute;
      var config = execute.config;
      var reserves = config.reserves;
      var pair = config.tradePairs[0];

      //用户信息
      info.userId = user.userId;
      info.avatar = user.avatar ? user.avatar : jconfig.img('view_image_portrait_normal.png');
      info.nickName = user.nickName;
      info.isFollow = user.isFollow;
      info.openCloseHome = user.openCloseHome;

      //策略名称
      info.strategyId = execute.strategyId;
      info.strategyName = execute.strategyName;

      //策略方向
      if (pair.investType!=undefined) {
        switch (Number(pair.investType)) {
          case 0:
            info.contractNum =  1;
            info.contractStr =  T('做多') + pair.leverRate + 'X';
            break;
          case 1:
            info.contractNum =  -1;
            info.contractStr =  T('做空') + pair.leverRate + 'X';
            break;
          case 2:
            info.contractNum =  0;
            info.contractStr =  T('双向') + pair.leverRate + 'X';
            break;
          default:
            break;
        }
      } 

      //交易对
      var pairStr;
      if (execute.executeType == 'FATHER') {
        pairStr = T('多币对')+ config.pairs.length;
      } else if (execute.isContract == 'spot') {
        pairStr = pair.counterCoin + '/' + pair.baseCoin;
      } else if (info.contractStr) {
        pairStr = pair.counterCoin + T('永续') + '/' + pair.baseCoin;
      }
      info.pairStr = pairStr;
      info.pairStrx = pair.exchangeName + '（'+ pairStr +'）';

      //启动时间
      info.startTime = jtime.getTime(execute.startTime);
      info.timeLnegth = jtime.getTimeLength(execute.startTime, undefined, 'dd天HH小时mm分');

      //投资币
      var investCoin =  pair.investCoin;
      info.investCoin = investCoin;

      //总投入
      var investCoinnNum = pair.investCoinnNum; 
      info.investCoinnNum = jmath.gfCoin(investCoinnNum, investCoin);

      //总收益
      var realEarnings = jmath.gfCoin(execute.realEarnings, investCoin);
      info.realEarnings = jmath.addJia(realEarnings);
      info.realEarningsRate = jmath.addJia(execute.realEarningsRate);

      if (execute.isContract == 'spot') {
      
        //实现盈亏
        var earnings = jmath.gfCoin(execute.earnings, investCoin);
        info.earnings = jmath.addJia(earnings);

        //浮动盈亏
        var floatEarnings = jmath.gfCoin(execute.floatEarnings, investCoin);
        info.floatEarnings = jmath.addJia(floatEarnings);
      } else if (info.contractStr) {

        //账户权益
        var marginBalance = jmath.gfCoin(position.marginBalance, investCoin);
        info.marginBalance = marginBalance>0 ? marginBalance : '--';

        //持仓盈亏
        var floatEarnings = jmath.gfCoin(position.profitUnreal, investCoin);
        info.floatEarnings = jmath.addJia(floatEarnings);
      }
       //总年化
      info.realYearIncome = jmath.addJia(execute.realYearIncome);

      //交易笔数、交易额、最大回撤
      info.orderNumber = tradeMoney.orderNumber;
      info.tradeMoney = jmath.gfCoin(tradeMoney.tradeMoney, investCoin);
      info.maxDrawdown = execute.maxDrawdown;
      
      /*********** 策略参数 */
      var params = [];
      //杠杠倍数
      if (info.contractStr) {
        var value = pair.leverRate+'X';
        params.push({'title':'杠杠倍数', value});
      }

      //参数
      var typesx = {
        '补仓金额模式':[T('倍数补仓'), T('增量补仓')],

        '补仓间隔模式':[T('固定间隔'), T('自定义间隔')],

        '补仓下单模式':[T('追踪补仓'), T('预埋单补仓')],

        '网格分布':[T('等比网格'), T('等差网格')],

        '止盈平仓模式':[T('一次性止盈'), T('逐单止盈')],

        '止盈下单模式':[T('追踪止盈'), T('预埋单止盈')],

        '利润模式':[T('赚')+pair.baseCoin, T('赚')+pair.counterCoin]
      }
      for (let index = 0; index < reserves.length; index++) {
        var item = reserves[index];

        //隐藏
        if (item.visiable==0) continue;

        //切换参数
        var types = typesx[item.name];
        if (types) {
          var value = Number(item.value);
          value = types[value];
          params.push({'title':item.name, value})
          continue;
        }

        //单位
        var unitName = '';
        if (item.valueType == 'percent') {
          unitName = ' %';
        } else  if (item.valueMax != 0 || item.valueMax != 0) {
          unitName = ' '+investCoin;
        }
        
        var value = item.option&&item.value==0 ?  '--' : (item.value + unitName);
        params.push({'title':item.name, value})
      }

      //止盈
      var value = config.stopProfit ? (jmath.cheng(config.stopProfit, '100', 2, 2) + ' %') : '--';
      params.push({'title':'总收益止盈', value})
      
      //止损
      var value = config.stopLoss ? (jmath.cheng(config.stopLoss, '-100', 2, 2) + ' %') : '--';
      params.push({'title':'总亏损止损', value})

      info.params = params;

      this.info = info;

      //复制启动需要配置
      this.copy = {'strategyId':execute.strategyId, 'strategyName':execute.strategyName, 'copyConfig':config};
    },

    //操作记录
    initLogs(datas) {

      var logs = [];
      datas.forEach((item)=>{
        
        var log = {};
        // "operation": "EDIT_PARAM",
        //START 启动,EDIT_PARAM 修改参数，SUSPEND 暂停，END终止，ADD_SCALE 加仓，SUB_SACLE 减仓
        //RESTART 策略重启,
        if (item.operation == 'START') {

          log['title'] = '[启动] ' + item.content;
        } else if (item.operation == 'SUSPEND') {

          log['title'] = '[暂停] ' + item.content;
        }  else if (item.operation == 'RESTART') {

          log['title'] = '[重启] ' + item.content;
        } else if (item.operation == 'END') {

          log['title'] = '[终止] ' + item.content;
        } else if (item.operation == 'ADD_SCALE') {

          log['title'] = '[加仓] ' + item.content;
        } else if (item.operation == 'SUB_SACLE') {

          log['title'] = '[减仓] '; + item.content;
        } else if (item.operation == 'EDIT_PARAM') {

          log['title'] = '[修改参数]';
          var text = '';
          for (let index = 0; index < item.content.length; index++) {
            var map = item.content[index];
            text = text + map.name + '：' + '['+map.oldValue+']' + ' --> ' +'['+map.newValue+']';
            if(index < item.content.length-1) {
              text = text + '\n';
            }
          }
          log['text'] = text;
        }
        log['time'] = jtime.getTime(item.createTime, 'M/d H:m:s');

        logs.push(log);
      })

      this.logs = logs;
    },

    /********************************** HTTP*/
    //http跟单策略详情
    httpQueryExecuteDetail() {

      jmodal.showLoad();
      var param = {'executeId': this.executeId};
      jhttps.post("execute/queryExecuteDetail",param,true,(data) => {
        jmodal.hideLoad();
        if (data.status == 200) {
          data = data.data;
          this.initData(data);
        } else {
          jmodal.toast(data.msg);
        }
      });
    },

    //操作记录
    httpQueryStrategyLogList(hud, menu) {

      hud && jmodal.showLoad();
      var param = {'executeId': this.executeId, 'pageNo':1};
      jhttps.post("execute/queryStrategyLogList",param,true,(data) => {
        hud && jmodal.hideLoad();
        if (data.status == 200) {
          this.initLogs(data.data);
          this.menu = hud ? menu : this.this.menu;
        } else {
          hud && jmodal.toast(data.msg);
        }
      });
    },

    //收益曲线
    httpQueryIncomeLine(hud, menu) {

      hud && jmodal.showLoad();
      var param = {'executeId': this.executeId};
      jhttps.post("execute/queryIncomeLine",param,true,(data) => {
        hud && jmodal.hideLoad();
        if (data.status == 200) {
          this.lineChartData = data.data;
          this.menu = hud ? menu : this.this.menu;
        } else {
          hud && jmodal.toast(data.msg);
        }
      });
    },

    //关注
    httpsFollowUser() {
      if (!jconfig.forceLogin()) return;

      jmodal.showLoad();
      var param = {'teacherUserId': this.info.userId};
      jhttps.post("followNew/followUser",param,true,(data) => {
        
        jmodal.hideLoad();
        if (data.status == 200) {
          this.info.isFollow = true;
          jmodal.toast('关注成功');
        } else {
          jmodal.toast(data.msg);
        }
      });
    },

    //取消关注
    httpsCancelFollowUser() {
      if (!jconfig.forceLogin()) return;

      jmodal.showLoad();
      var param = {'teacherUserId': this.info.userId};
      jhttps.post("followNew/cancelFollowUser",param,true,(data) => {
        
        jmodal.hideLoad();
        if (data.status == 200) {
          this.info.isFollow = false;
          jmodal.toast('取注成功');
        } else {
          jmodal.toast(data.msg);
        }
      });
    },

    //http用户信息
    httpUserInfo() {
      if (!jconfig.isLogin) {
        this.isVip = false;
        return;
      }

      var param = {};
      jhttps.postX("userV2/userDetail", param, true,(data) => {
        if (data.status == 200) {
          data = data.data;
          var info = data.account;
          this.isVip = info.member != 'LV0';
        } else {
        }
      });
    },

    //http查询复制信息（价格、是否支付过）
    httpGetCopyStrategyParamInfo() {
      jmodal.showLoad();
      var param = {'executeId': this.executeId};
      jhttps.post("execute/getCopyStrategyParamInfo", param, true,(data) => {
        jmodal.hideLoad();
        if (data.status == 200) {
          
          data = data.data;
          if (data.isNeedVtn) {
            jmodal.hideLoad();
            var parm = {message:T("复制该策略参数需要支付")+data.copyNeedVtn+'VTN(含提现权益)。',
                        okBtn:T("支付"), cancelBtn:T("取消")};
            jmodal.confirm(parm, (bool)=>{
              if(bool == "true") {
                this.httpGetCopyStrategyParam();
              }
            });
          } else {
            this.copyUp();
          }

        } else {
          jmodal.toast(data.msg);
        }
      });
    },

    //http复制参数
    httpGetCopyStrategyParam() {
      jmodal.showLoad();
      var param = {'executeId': this.executeId};
      jhttps.postX("execute/copyStrategyParam", param, true,(data) => {
        jmodal.hideLoad();
        if (data.status == 200) {
          this.copyUp();
        } else {
          jmodal.toast(data.msg);
        }
      });
    },
    
    /********************************** 点击方法*/
    //有按钮-分享
    rightBtn(){
      
      jvlink.getFollw(this.executeId, (vcode, vtip)=>{
        
        var param = {'avatar':this.info.avatar,
                    'nickName':this.info.nickName,
                    'strategyName':this.info.strategyName,
                    'realEarningsRate':this.info.realEarningsRate,
                    'realYearIncome':this.info.realYearIncome,
                    'pairStr':this.info.pairStr,
                    'timeLnegth':this.info.timeLnegth};
        param = {'param':param, 
                 'vcode':vcode,
                 'vtip':vtip};
        weexFunction.shareWeex('share/ShareLaunchx', param);
      });
    },

    //菜单点击
    menuClick(menu) {
      if (menu == 2 && !this.lineChartData) {
        this.httpQueryIncomeLine(true, menu);
        return;
      }

      if(menu == 1 && !this.logs) {
        this.httpQueryStrategyLogList(true, menu);
        return;
      }

      this.menu = menu;
    },

    //开通VIP
    opVipClick() {
      if (!jconfig.forceLogin()) return;
      jnavigator.open('', "mine/Vip", {}, {'navColor':'#1677fe'});
    },

    //复制启动点击
    copyClick() {

      if (!jconfig.forceLogin()) return;

      this.httpGetCopyStrategyParamInfo();
    },

    //复制启动
    copyUp() {

      var dict = {'网格交易': 'up/SUpGrid',
                    '海浪网格': 'up/SUpSea',
                    '马丁追踪': 'up/SUpMd',
                    '区间套利': 'up/SUpQj',
                    '恒量定投': 'up/SUpWeigh',
                    '海风马丁': 'up/SUpHf',
                    '币本位海风马丁': 'up/SUpHfTb',
                    'DCA智能策略': 'up/SUpTy'};
      var url = this.info.contractStr ? 'upContract/CUp' : dict[this.info.strategyName];
      weexFunction.debugLog('ddd'+url)
      if (!url){
        jmodal.toast('无法复制非官方策略');
        return;
      }
      jnavigator.open(this.copy.strategyName, url, this.copy);
    },

    //用户详情
    userClick() {

      if (!this.info.openCloseHome) {
        // jmodal.toast('该用户未开放放主页');
        return;
      }

      var param = {'userId':this.info.userId};
      jnavigator.open('', "follw/UFollwManInfo",param);
    },
  },
};

</script>


<style src="@/_css/style.css"></style>
<style scoped>
/***********************************基础*/
.bg {
  width: 750px;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
.scroller {
  flex: 1;
  flex-direction: column;
}
.wrapper {
  width: 750px;
  flex-direction: column;
}

/*********************************** 头部*/
.head {
  flex-direction: column;
  width: 750px;
  padding: 40px;
}
.img-avatar {
  width: 96px;
  height: 96px;
  border-radius: 48px;

  margin-right: 30px;
}
.but-follow {
  align-items: center;
  justify-content: center;
  height: 44px;
  border-radius: 6px;
  padding: 0 20px;
  margin-left: 30px;
}
.contrac{
  height: 32px;
  border-radius: 4px;
  padding: 0 10px;
  margin-left: 10px;
}

/*********************************** 策略表现*/
.title {
  display: flex;
  flex-direction: row;
  padding: 40px 0 30px 20px;
}
.line{
  width: 6px;
  height: 28px;
  border-radius: 3px;

  margin-right: 16px;
  margin-bottom: 20px;
}
.strategy{
  overflow: hidden;
  margin: 0 20px 20px 20px;
  border-top-left-radius: 20px;
  border-bottom-left-radius: 2px;
  border-bottom-right-radius: 2px;
}
.strategy-info{
  flex-direction: row;
  justify-content: space-between;
  border-top-left-radius: 20px;
  border-bottom-right-radius: 20px;

  padding: 20px 40px;
}
.strategy-data{
  flex-direction: column;
  padding: 40px;
}

/*********************************** 分类*/
.menu {
  padding: 20px;
}
.content {
  flex-direction: column;
  min-height: 800px;
}
.size {
  padding: 40px;
  margin: 0 20px 20px 20px;
  border-radius: 4px;
}
.size-text {
  font-size: 24; 
  line-height: 50px;
}

.line-chart {
  margin-top: 40px;
  height: 450px;
}
.line-chart-color{
  width: 20px;
  height: 12px;
  border-radius: 2px;
  
  margin-right: 20px;
}

.vip-tips {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;

  align-items: center;
  /* justify-content: center; */
  background-color: rgba(18, 29, 57, 0.8);  
  -webkit-backdrop-filter: blur(50px);
  backdrop-filter: blur(50px);
}
.img-sigh {
  width: 48px;
  height: 48px;
  margin-top: 40px;
  margin-bottom: 20px;
}
.vip-but {
  align-items: center;
  justify-content: center;
  width: 352px;
  height: 60px;
  border-radius: 40px;
}

/*********************************** 按钮*/
.bottom{
  flex-direction: row;
  justify-content: center;
  width: 750px;
  height: 164px;
  padding-top: 30px;
}
.but {
  width: 520px;
  height: 80px;
  border-radius: 4px;
  align-items: center;
  justify-content: center;
}
</style>
